import java.util.ArrayList;
import java.util.List;

public class Solution1 {
    int[] tmpn;
    int[] tmpi;
    int[] index; // 标记 nums 中当前元素的原始下标
    int n;
    int[] ret;
    public List<Integer> countSmaller(int[] nums) {
        n = nums.length;
        tmpi = new int[n];
        tmpn = new int[n];
        index = new int[n];
        ret = new int[n];
        List<Integer> ret1 = new ArrayList<>();

        //初始化 index 数组
        for(int i = 0; i < n; i++) {
            index[i] = i;
        }
        mergeSort(nums, 0, n - 1);
        for(int i = 0; i < n; i++) {
            ret1.add(ret[i]);
        }
        return ret1;
    }

    public void mergeSort(int[] nums, int left, int right) {
        if(left >= right) {
            return;
        }

        // 1. 根据中间元素划分区间
        int mid = (left + right) / 2;
        // [left, mid] [mid + 1, right]

        // 2. 处理左右两个区间
        mergeSort(nums, left, mid);
        mergeSort(nums, mid + 1, right);

        // 3. 处理一左一右的情况
        int cur1 = left;
        int cur2 = mid + 1;
        int i = 0;
        while(cur1 <= mid && cur2 <= right) { // 降序排序
            if(nums[cur1] <= nums[cur2]) {
                tmpn[i] = nums[cur2];
                tmpi[i] = index[cur2];
                i++;
                cur2++;
            }else {
                ret[index[cur1]] += right - cur2 + 1; // 记录 nums[cur1] 右边有多少个比它小的数（重点）
                tmpn[i] = nums[cur1];
                tmpi[i] = index[cur1];
                i++;
                cur1++;
            }
        }

        // 4. 处理剩余的工作
        while(cur1 <= mid) {
            tmpn[i] = nums[cur1];
            tmpi[i] = index[cur1];
            i++;
            cur1++;
        }
        while(cur2 <= right) {
            tmpn[i] = nums[cur2];
            tmpi[i] = index[cur2];
            i++;
            cur2++;
        }

        // 5. 还原
        for(int j = left; j <= right; j++) {
            nums[j] = tmpn[j - left];
            index[j] = tmpi[j - left];
        }
    }
}
